package com.inhim.pjhim.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.adapter.RadioBottomDialogAdapter;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.dowloadfile.download.DownloadInfo;
import com.inhim.pjhim.dowloadfile.download.MyBusinessInfoDid;
import com.inhim.pjhim.dowloadfile.download.limit.DownloadLimitManager;
import com.inhim.pjhim.entity.DownloadAuthor;
import com.inhim.pjhim.entity.ProjectListEntity;
import com.inhim.pjhim.entity.ReaderInfo;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.notification.NotifyHelper;
import com.inhim.pjhim.utils.GlideUtils;
import com.inhim.pjhim.utils.ImageLoaderUtils;
import com.inhim.pjhim.utils.PrefUtils;
import com.inhim.pjhim.utils.TextViewUils;
import com.inhim.pjhim.utils.WXShareUtils;
import com.inhim.pjhim.view.BToast;
import com.inhim.pjhim.view.BottomDialog;
import com.inhim.pjhim.view.CenterDialog;
import com.inhim.pjhim.view.CircleImageView;
import com.inhim.pjhim.view.CustomRoundAngleImageView;
import com.pili.pldroid.player.AVOptions;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCMediaManager;
import fm.jiecao.jcvideoplayer_lib.JCRadioPlayerStandard;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import okhttp3.Request;

//单个章节
@SuppressLint("SetJavaScriptEnabled")
public class RadioActivity extends BaseActivity implements
        JCRadioPlayerStandard.ShowListDialogListener {

    ImageView iv_back;
    TextView iv_share;
    String name;
    public static String contents;
    private String photoUrl;

    JCRadioPlayerStandard mJcVideoPlayerStandard;
    private boolean mIsLiveStreaming = false;
    Long id;
    String videoUrl, videoPath;
    File videoFile;
    private String results;
    private String vedioName;
    private ReaderInfo.Reader readerInfo;
    private CheckBox checkbox;
    private RadioButton iv_download;
    private Gson gson;
    //下载得视频 课程
    private MyBusinessInfoDid businessInfoDid;
    WebView webView;
    final String mimeType = "text/html";
    final String encoding = "UTF-8";
    private String title;
    private String description;
    private TextView textview1, textview2, textview3, textview4, textview6, textview;
    //private AudioManager audio;
    private String fromTAG;
    private CustomRoundAngleImageView iv_title;
    private TextView tv_name;
    private TextView tv_author_name,tv_author_pastor,tv_author_from,tv_author_content;
    private CircleImageView iv_author_photo;
    private RadioBottomDialogAdapter mAdapter;
    private int mPlayPosition;
    private boolean mIsPlay=false;
    private boolean mIsFirst=false;
    private List<ProjectListEntity.List> mProjectListEntitys;
    private int mPageNum=1;
    private Boolean refresh=true;
    private int totalPage;
    private DownloadAuthor mDownloadAuthor;
    private ConstraintLayout in_author;
    private MyApplication myApplication;
    @Override
    public Object offerLayout() {
        return R.layout.activity_radio;
    }

    @Override
    public void onBindView() {
        hideFloat();
        myApplication=new MyApplication();
        mProjectListEntitys=new ArrayList<>();
        //audio = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        gson = new Gson();
        initView();
        mIsFirst=true;
        fromTAG = getIntent().getStringExtra("TAG");
        readerInfo = (ReaderInfo.Reader) getIntent().getSerializableExtra("readerInfo");
        businessInfoDid = (MyBusinessInfoDid) getIntent().getSerializableExtra("result");
        //判断 是已下载视频 且内存中视频未被删除
        if (businessInfoDid != null && (new File(businessInfoDid.getFilePath())).exists()) {
            loadDownloadContent(businessInfoDid);
        } else {
            if (fromTAG != null && fromTAG.equals("ChatView") && readerInfo != null) {
                loadContent(null,readerInfo);
            } else {
                getReaderInfo(getIntent().getIntExtra("ReaderId", 0));
            }
        }
        mAdapter = new RadioBottomDialogAdapter(RadioActivity.this);
        mAdapter.setOnItemChildClickListener((view, position) -> {
            //CollectionList.List collection = adapter.getAllData().get(position);
            switch (view.getId()) {
                case R.id.checkbox_collect:
                    CheckBox checkbox_collect = (CheckBox) view;
                    collectionReader(checkbox_collect,mAdapter.getAllData().get(position).getReaderId());
                    break;
                case R.id.checkbox_download:
                    RadioButton checkbox_download = (RadioButton) view;
                    //checkbox_download.setChecked(videoFile.exists());
                    vedioName = mAdapter.getAllData().get(position).getUrl().substring(mAdapter.getAllData().get(position).getUrl().lastIndexOf("/"));
                    String videoPaths = Urls.getFilePath() + vedioName;
                    File videoFiles = new File(videoPaths);
                    if(videoFiles.exists()){
                        BToast.showText("您已下载该音频");
                        return;
                    }
                    downloadReaderInfo(mAdapter.getAllData().get(position).getReaderId());
                    break;
            }
        });
        mAdapter.setOnItemClickListener(position -> {
            mMainHander.removeCallbacksAndMessages(null);
            JCVideoPlayer.releaseAllVideos();
            mMainHander.postDelayed(() -> {
                mPlayPosition=position;
                mAdapter.setReaderId(mProjectListEntitys.get(position).getReaderId());
                mAdapter.notifyDataSetChanged();
                mIsPlay=true;
                getReaderInfo(mProjectListEntitys.get(position).getReaderId());
            },400);

        });
    }

    private Handler mMainHander=new Handler();

    private void collectionReader(CheckBox mCheckBox,int readerId){
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncJsonPost(Urls.collectionReader(readerId), new HashMap(),
                new MyOkHttpClient.HttpCallBack() {
                    @Override
                    public void onError(Request request, IOException e) {
                        /*if (mCheckBox.isChecked()) {
                            mCheckBox.setChecked(false);
                        } else {
                            mCheckBox.setChecked(true);
                        }*/
                    }

                    @Override
                    public void onSuccess(Request request, String result) {
                        hideLoading();
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getInt("code") != 0) {
                                BToast.showText(jsonObject.getString("msg"), false);
                                //收藏失败时将按钮状态还原
                                /*if (mCheckBox.isChecked()) {
                                    mCheckBox.setChecked(false);
                                } else {
                                    mCheckBox.setChecked(true);
                                }*/
                            } else {
                                if (mCheckBox.isChecked()) {
                                    BToast.showText("收藏成功", true);
                                } else {
                                    BToast.showText("已取消收藏", true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @Override
    public void destory() {
        //JCVideoPlayer.releaseAllVideos();
        mMainHander.removeCallbacksAndMessages(null);
        /*mNotifyHelper = NotifyHelper.getInstance(this);
        mstartForeground();*/
    }

    private NotifyHelper mNotifyHelper;
    private static final String CHANNEL_ID = "music_channel_id";
    private static final String CHANNEL_NAME = "music_channel_name";
    private static final String CHANNEL_DESCRIPTION = "music_channel_description";
    private RemoteViews notifyLayout;
    /**
     * 更改了相关设置，比如notifyLayout布局显示之后，需要重新发送前台通知来更新UI
     * 太坑了，居然是这样的
     *  此外，由于我们是显示成一个播放器，因此通知id，使用固定id，就可以保证每次更新之后是同一个通知。
     * @param picture 设置播放器图标为指定音乐图标,此对象属于MVC开发模式的model层数据
     */
    private void mstartForeground() {
        mNotifyHelper.CreateChannel(CHANNEL_ID, CHANNEL_NAME, CHANNEL_DESCRIPTION,mJcVideoPlayerStandard);
        notifyLayout = new RemoteViews(RadioActivity.this.getPackageName(), R.layout.layout_radio_notification);
        final Notification notification = mNotifyHelper.createForeNotification(CHANNEL_ID, notifyLayout);
        Intent intentPlay = new Intent("play");//新建意图，并设置action标记为"play"，用于接收广播时过滤意图信息
        PendingIntent pIntentPlay = PendingIntent.getBroadcast(this, 0,
                intentPlay, 0);
        notifyLayout.setOnClickPendingIntent(R.id.iv_music_play, pIntentPlay);//为play控件注册事件

        /*Intent intentPause = new Intent("pause");
        PendingIntent pIntentPause = PendingIntent.getBroadcast(this, 0,
                intentPause, 0);
        contentView.setOnClickPendingIntent(R.id.iv_music_play, pIntentPause);*/

        Intent intentNext = new Intent("next");
        PendingIntent pIntentNext = PendingIntent.getBroadcast(this, 0,
                intentNext, 0);
        notifyLayout.setOnClickPendingIntent(R.id.iv_music_next_song, pIntentNext);

        Intent intentLast = new Intent("last");
        PendingIntent pIntentLast = PendingIntent.getBroadcast(this, 0,
                intentLast, 0);
        notifyLayout.setOnClickPendingIntent(R.id.iv_music_last_song, pIntentLast);

        Intent intentCancel = new Intent("cancel");
        PendingIntent pIntentCancel = PendingIntent.getBroadcast(this, 0,
                intentCancel, 0);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, notification);
        //initNotificationBar();
    }

    private Notification notification;
    public void initNotificationBar() {
        notification = new Notification();
        //初始化通知
        notification.icon = R.drawable.ic_launcher;
        RemoteViews contentView = new RemoteViews(getPackageName(),
                R.layout.layout_radio_notification);
        notification.contentView = contentView;

        Intent intentPlay = new Intent("play");//新建意图，并设置action标记为"play"，用于接收广播时过滤意图信息
        PendingIntent pIntentPlay = PendingIntent.getBroadcast(this, 0,
                intentPlay, 0);
        contentView.setOnClickPendingIntent(R.id.iv_music_play, pIntentPlay);//为play控件注册事件

        /*Intent intentPause = new Intent("pause");
        PendingIntent pIntentPause = PendingIntent.getBroadcast(this, 0,
                intentPause, 0);
        contentView.setOnClickPendingIntent(R.id.iv_music_play, pIntentPause);*/

        Intent intentNext = new Intent("next");
        PendingIntent pIntentNext = PendingIntent.getBroadcast(this, 0,
                intentNext, 0);
        contentView.setOnClickPendingIntent(R.id.iv_music_next_song, pIntentNext);

        Intent intentLast = new Intent("last");
        PendingIntent pIntentLast = PendingIntent.getBroadcast(this, 0,
                intentLast, 0);
        contentView.setOnClickPendingIntent(R.id.iv_music_last_song, pIntentLast);

        Intent intentCancel = new Intent("cancel");
        PendingIntent pIntentCancel = PendingIntent.getBroadcast(this, 0,
                intentCancel, 0);
        //contentView.setOnClickPendingIntent(R.id.bt_notic_cancel, pIntentCancel);
        notification.flags = notification.FLAG_NO_CLEAR;//设置通知点击或滑动时不被清除
        //notify(CHANNEL_ID, notification);//开启通知
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, notification);

    }
    @Override
    protected void onStop() {
        super.onStop();
    }

    private void getReaderInfo(int readerId) {
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncGet(Urls.getReaderInfo(readerId, PrefUtils.getString("token", "")), new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
            }

            @Override
            public void onSuccess(Request request, String result) {
                ReaderInfo readerInfos = gson.fromJson(result, ReaderInfo.class);
                if (readerInfos.getCode() == 000) {
                    results = result;
                    loadContent(readerInfos,null);
                }
            }
        });
    }


    private void downloadReaderInfo(int readerId) {
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncGet(Urls.getReaderInfo(readerId, PrefUtils.getString("token", "")), new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
            }

            @Override
            public void onSuccess(Request request, String result) {
                ReaderInfo readerInfos = gson.fromJson(result, ReaderInfo.class);
                if (readerInfos.getCode() == 000) {
                    dowload(result);
                }
            }
        });
    }


    private void loadDownloadContent(MyBusinessInfoDid businessInfoDid) {
        if(businessInfoDid!=null ){
            List<DownloadAuthor> downloadAuthors = LitePal.where("readerId = ?", businessInfoDid.getReaderId()).find(DownloadAuthor.class);
            if(downloadAuthors.size()>0){
                mDownloadAuthor=downloadAuthors.get(0);
            }
            if(mDownloadAuthor!=null){
                TextViewUils.setText(tv_author_name,mDownloadAuthor.getName());
                TextViewUils.setText(tv_author_pastor,mDownloadAuthor.getIdentity());
                TextViewUils.setText(tv_author_from,"来自:"+mDownloadAuthor.getArea());
                TextViewUils.setText(tv_author_content,mDownloadAuthor.getSynopsis());
                ImageLoaderUtils.setImage(mDownloadAuthor.getHeadPortrait(),iv_author_photo);
                //textview6.setText("作者：" + mDownloadAuthor.getName());
                //textview6.setText("上传时间："+readerInfo.getCreateTime());
            }
        }
        TextViewUils.setText(tv_name,businessInfoDid.getReaderTypeText());
        title = businessInfoDid.getTitle();
        description = businessInfoDid.getSynopsis();
        if (description != null && !"".equals(description)) {
            textview.setVisibility(View.VISIBLE);
            textview.setText(description);
        }
        checkbox.setChecked(Boolean.valueOf(businessInfoDid.getCollectionStatus()));
        name = businessInfoDid.getTitle();
        contents = businessInfoDid.getContent();
        photoUrl = businessInfoDid.getCover();
        videoPath = businessInfoDid.getFilePath();
        videoUrl = businessInfoDid.getUrl();
        /*if(JCMediaManager.instance().mediaPlayer.isPlaying() && JCMediaManager.instance().CURRENT_PLAYING_URL.equals(videoUrl)){
            mJcVideoPlayerStandard.setIconStatus();
        }*/
        GlideUtils.displayFromUrl(businessInfoDid.getCover(),iv_title,this);
        videoFile = new File(videoPath);
        if(videoFile.exists()){
            iv_download.setChecked(true);
        }
        textview1.setText(businessInfoDid.getTitle());
        if(businessInfoDid.getTagName()==null || "".equals(businessInfoDid.getTagName())){
            textview2.setVisibility(View.GONE);
        }else{
            textview2.setVisibility(View.VISIBLE);
            TextViewUils.setText(textview2,"分类:"+businessInfoDid.getTagName());
        }
        textview3.setText(String.valueOf(businessInfoDid.getReadAmount()));
        textview4.setText(businessInfoDid.getTimeText());
        setVideo(videoPath);
    }

    // 按返回键退出
    long previous = 0;

   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            *//*case KeyEvent.KEYCODE_VOLUME_UP:
                if (audio != null) {
                    audio.adjustStreamVolume(
                            AudioManager.STREAM_MUSIC,
                            AudioManager.ADJUST_RAISE,
                            AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (audio != null) {
                    audio.adjustStreamVolume(
                            AudioManager.STREAM_MUSIC,
                            AudioManager.ADJUST_LOWER,
                            AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                }
                return true;*//*
            case 4:
                try {
                    if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                        *//*if (System.currentTimeMillis() - previous > 4000) {
                            BToast.showText("再按一次退出");
                            previous = System.currentTimeMillis();
                        } else {*//*
                            showFloat(readerInfo, businessInfoDid);
                            //finish();
                        //}
                    } else {
                        //finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //finish();
                }
                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }*/

    private void loadContent(ReaderInfo readerInfos,ReaderInfo.Reader readers) {
        if(readers!=null){
            readerInfo=readers;
        }else{
            readerInfo = readerInfos.getReader();
        }
        if(readerInfo.getReaderTypeText()!=null){
            tv_name.setText(readerInfo.getReaderTypeText());
        }
        if(readerInfo!=null && readerInfo.getAuthor()!=null){
            tv_author_name.setVisibility(View.VISIBLE);
            TextViewUils.setText(tv_author_name,readerInfo.getAuthor().getName());
            TextViewUils.setText(tv_author_pastor,readerInfo.getAuthor().getIdentity());
            TextViewUils.setText(tv_author_from,"来自:"+readerInfo.getAuthor().getArea());
            TextViewUils.setText(tv_author_content,readerInfo.getAuthor().getSynopsis());
            ImageLoaderUtils.setImage(readerInfo.getAuthor().getHeadPortrait(),iv_author_photo);
        }else{
            tv_author_name.setVisibility(View.GONE);
        }
        title = readerInfo.getTitle();
        description = readerInfo.getSynopsis();
        if (description != null && !"".equals(description)) {
            textview.setVisibility(View.VISIBLE);
            textview.setText(description);
        }
        GlideUtils.displayFromUrl(readerInfo.getCover(),iv_title,this);
        checkbox.setChecked(readerInfo.getCollectionStatus());
        name = readerInfo.getTitle();
        if (readerInfo.getUrl() != null) {
            videoUrl = readerInfo.getUrl();
            vedioName = readerInfo.getUrl().substring(readerInfo.getUrl().lastIndexOf("/"));
        }
        contents = readerInfo.getContent();
        photoUrl = readerInfo.getCover();
        videoPath = Urls.getFilePath() + vedioName;
        videoFile = new File(videoPath);
        iv_download.setChecked(videoFile.exists());
        textview1.setText(readerInfo.getTitle());
        if(readerInfo.getTagName()==null || "".equals(readerInfo.getTagName())){
            textview2.setVisibility(View.GONE);
        }else{
            textview2.setVisibility(View.VISIBLE);
            textview2.setText(readerInfo.getTagName());
        }
        if (null != readerInfo.getAuthor()) {
            //textview6.setText("作者：" + readerInfo.getAuthor().getName());
        }
        //textview6.setText("上传时间："+readerInfo.getCreateTime());
        textview3.setText(readerInfo.getReadAmount()+"人已听");
        if(readerInfo.getCreateTime()!=null){
            textview4.setText(readerInfo.getCreateTime());
        }
        if (fromTAG != null && fromTAG.equals("ChatView")) {
        } else {
            //JCVideoPlayer.releaseAllVideos();
        }
        if(mIsFirst){
            getReaderList();
        }else{
            setVideo("");
        }
    }

    private void dowload(String result) {
        rxPermissionWriteAndRead(result);
    }

    private void rxPermissionWriteAndRead(String result) {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (RadioActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    RadioActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    //这里就是权限打开之后自己要操作的逻辑
                    List<DownloadInfo> person = null;
                    //查找当前url文件是否正在下载中
                    if (businessInfoDid != null) {
                        person = LitePal.where("url = ?", businessInfoDid.getUrl()).find(DownloadInfo.class);
                    } else {
                        try {
                            person = LitePal.where("url = ?", readerInfo.getUrl()).find(DownloadInfo.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (videoFile != null && videoFile.exists()) {
                        BToast.showText("已下载");
                    }else  if ((person != null && person.size() > 0)) {
                    /*Intent intent = new Intent(RadioActivity.this, ListActivity.class);
                    startActivity(intent);*/
                        //DownloadLimitManager.getInstance().download(readerInfo.getUrl());
                        BToast.showText("正在下载");
                    } else {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            DownloadInfo businessInfo = gson.fromJson(jsonObject.getJSONObject("reader").toString(), DownloadInfo.class);
                            businessInfo.setFilePath(videoPath);
                            businessInfo.setProgress(0);
                            businessInfo.setProgressText("0");
                            businessInfo.setFileName(businessInfo.getUrl().substring(businessInfo.getUrl().lastIndexOf("/")));
                            businessInfo.setDownloadStatus("download");
                            boolean istrue = businessInfo.save();
                            DownloadAuthor saveAuthor=new DownloadAuthor();
                            saveAuthor.setReaderId(readerInfo.getReaderId());
                            /*if(readerInfo.getAuthor()!=null){
                                in_author.setVisibility(View.VISIBLE);
                                saveAuthor.setArea(readerInfo.getAuthor().getArea());
                                saveAuthor.setCreateTime(readerInfo.getAuthor().getCreateTime());
                                saveAuthor.setHeadPortrait(readerInfo.getAuthor().getHeadPortrait());
                                saveAuthor.setId(readerInfo.getAuthor().getId());
                                saveAuthor.setIdentity(readerInfo.getAuthor().getIdentity());
                                saveAuthor.setName(readerInfo.getAuthor().getName());
                                saveAuthor.setSynopsis(readerInfo.getAuthor().getSynopsis());
                            }else{
                                in_author.setVisibility(View.GONE);
                            }*/
                            saveAuthor.save();
                            if (istrue) {
                            /*Intent intent = new Intent(RadioActivity.this, ListActivity.class);
                            startActivity(intent);*/
                                BToast.showText("正在下载");
                                DownloadLimitManager.getInstance().download(businessInfo.getUrl());
                                DownloadLimitManager.getInstance().setTitle(businessInfo.getTitle());
                            } else {
                                iv_download.setChecked(false);
                                BToast.showText("下载失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        hideActionBar();
    }

    @Override
    protected void onPause() {
        super.onPause();
        /*mNotifyHelper = NotifyHelper.getInstance(this);
        mstartForeground();*/
        try {
            if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                showFloat(readerInfo, businessInfoDid);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //当前播放进度
        if (businessInfoDid != null) {
            int position = mJcVideoPlayerStandard.getCurrentPositionWhenPlaying();
            //获取当前播放进度
            int duration = getDuration();
            float num = (float) position / duration;
            DecimalFormat df = new DecimalFormat("0.00");//格式化小数
            String progressTime = df.format(num);//返回的是String类型
            //格式化fat,保留两位小数, 得到一个string字符串
            if (progressTime != null && !progressTime.equals("NaN")) {
                DecimalFormat decimalFormat = new DecimalFormat(".00");
                String proess = decimalFormat.format(Float.valueOf(progressTime) * 100);
                MyBusinessInfoDid myBusinessInfoDid = new MyBusinessInfoDid();
                //第二步，改变某个字段的值
                myBusinessInfoDid.setProgressText("已观看" + proess + "%");
                //第三步，保存数据
                //更新所有readerId为readerId的记录,记录观看进度
                myBusinessInfoDid.updateAll("readerId = ?", businessInfoDid.getReaderId());
            }
        }
    }

    public int getDuration() {
        //视频总时间
        int duration = 0;
        if (JCMediaManager.instance().mediaPlayer == null) return duration;
        try {
            duration = JCMediaManager.instance().mediaPlayer.getDuration();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return duration;
        }
        return duration;
    }

    private void initView() {
        in_author=findViewById(R.id.in_author);
        tv_author_name = findViewById(R.id.tv_author_name);
        tv_author_pastor = findViewById(R.id.tv_author_pastor);
        tv_author_from = findViewById(R.id.tv_author_from);
        tv_author_content = findViewById(R.id.tv_author_content);
        iv_author_photo = findViewById(R.id.iv_author_photo);
        tv_name=findViewById(R.id.tv_name);
        iv_title =findViewById(R.id.iv_title);
        textview = findViewById(R.id.textview);
        textview1 = findViewById(R.id.textview1);
        textview2 = findViewById(R.id.textview2);
        textview3 = findViewById(R.id.textview3);
        textview4 = findViewById(R.id.textview4);
        textview6 = findViewById(R.id.textview6);
        iv_share = findViewById(R.id.iv_share);
        iv_share.setOnClickListener(v -> {
            if (businessInfoDid != null) {
                WXShareUtils.show(RadioActivity.this, Urls.shareH5(Integer.valueOf(businessInfoDid.getReaderId())), title, description);
            } else {
                WXShareUtils.show(RadioActivity.this, Urls.shareH5(readerInfo.getReaderId()), title, description);
            }
        });
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(v -> {
            try {
                if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                    /*if (System.currentTimeMillis() - previous > 4000) {
                        BToast.showText("再按一次退出");
                        previous = System.currentTimeMillis();
                    } else {*/
                        showFloat(readerInfo, businessInfoDid);
                        finish();
                    //}
                } else {
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
                finish();
            }
        });
        checkbox = findViewById(R.id.checkbox);
        iv_download=findViewById(R.id.iv_download);
        mJcVideoPlayerStandard = findViewById(R.id.jc_video);
        mJcVideoPlayerStandard.setListener(RadioActivity.this);
        webView = findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        //设置 缓存模式
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        webView.getSettings().setDomStorageEnabled(true);
        checkbox.setOnClickListener(v -> {
            if(readerInfo!=null){
                collectionReader(checkbox,readerInfo.getReaderId());
            }
        });

        iv_download.setOnClickListener(v -> {
            //iv_download.setChecked(videoFile.exists());
            if (videoFile!=null&&videoFile.exists()) {
                BToast.showText("已下载");
            }
            dowload(results);
        });
    }


  /*  @Override
    public void onBackPressed() {
        *//*if (JCVideoPlayer.backPress()) {
            return;
        }*//*
        super.onBackPressed();
    }*/
  private final String isPlayingKey="playingRadio";
    private final String isPlayingUrl="playingUrl";
    private void setVideo(String videoUrls) {
        if (contents == null || contents.length() == 0) {
            contents = "暂无内容";
        }
        webView.loadDataWithBaseURL(null, contents, mimeType, encoding, null);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        if (videoFile.exists()) {
            mJcVideoPlayerStandard.setUp(videoPath
                    , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, name);
            try {
                if(JCMediaManager.instance().mediaPlayer.isPlaying() && JCMediaManager.instance().CURRENT_PLAYING_URL.equals(videoPath)){
                    PrefUtils.putBoolean(isPlayingKey,false);
                    PrefUtils.putString(isPlayingUrl,"");
                    mJcVideoPlayerStandard.playRadio();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        } else {
            mJcVideoPlayerStandard.setUp(mradioUrls
                    , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, mPlayPosition);
            try {
                if(JCMediaManager.instance().mediaPlayer.isPlaying() && JCMediaManager.instance().CURRENT_PLAYING_URL.equals(videoUrl)){
                    //mJcVideoPlayerStandard.setIconStatus();
                    mJcVideoPlayerStandard.playRadio();
                    PrefUtils.putBoolean(isPlayingKey,false);
                    PrefUtils.putString(isPlayingUrl,"");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //ImageLoaderUtils.setImage(photoUrl,mJcVideoPlayerStandard.thumbImageView);

        //屏幕保持常亮
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // 1 -> hw codec enable, 0 -> disable [recommended]
        int codec = getIntent().getIntExtra("mediaCodec", AVOptions.MEDIA_CODEC_SW_DECODE);
        AVOptions options = new AVOptions();
        // the unit of timeout is ms
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        // 1 -> hw codec enable, 0 -> disable [recommended]
        options.setInteger(AVOptions.KEY_MEDIACODEC, codec);
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, mIsLiveStreaming ? 1 : 0);
        boolean disableLog = getIntent().getBooleanExtra("disable-log", false);
        options.setInteger(AVOptions.KEY_LOG_LEVEL, disableLog ? 5 : 0);
        boolean cache = getIntent().getBooleanExtra("cache", false);
        if (!mIsLiveStreaming && cache) {
            options.setString(AVOptions.KEY_CACHE_DIR, Urls.getFilePath());
        }
        boolean vcallback = getIntent().getBooleanExtra("video-data-callback", false);
        if (vcallback) {
            options.setInteger(AVOptions.KEY_VIDEO_DATA_CALLBACK, 1);
        }
        if (fromTAG != null && fromTAG.equals("ChatView")) {
            if(mJcVideoPlayerStandard!=null){
                mJcVideoPlayerStandard.playRadio();
                PrefUtils.putBoolean(isPlayingKey,false);
                PrefUtils.putString(isPlayingUrl,"");
            }
        }
        if(mIsPlay){
            if(mJcVideoPlayerStandard!=null){
                mJcVideoPlayerStandard.playRadio();
                PrefUtils.putBoolean(isPlayingKey,false);
                PrefUtils.putString(isPlayingUrl,"");
            }
        }

    }

    @Override
    public void showListDialog() {
        if(businessInfoDid!=null){
            return;
        }
        if(mAdapter!=null && readerInfo!=null){
            mAdapter.setReaderId(readerInfo.getReaderId());
        }
        if(mBottomDialog!=null){
            mBottomDialog.show();
        }else{
            setDiaglog();
            mBottomDialog.show();
        }
    }

    @Override
    public void lastRadio() {
        if(mAdapter!=null && mProjectListEntitys!=null &&mProjectListEntitys.size()>0){
            if(mPlayPosition!=0){
                mPlayPosition--;
                mIsPlay=true;
                mAdapter.setReaderId(mProjectListEntitys.get(mPlayPosition).getReaderId());
                getReaderInfo(mProjectListEntitys.get(mPlayPosition).getReaderId());
                setVideo("");
            }
        }
    }

    @Override
    public void nextRadio(int playPosition) {
        if(mAdapter!=null && mProjectListEntitys!=null &&mProjectListEntitys.size()>0){
            if(mPlayPosition!=mProjectListEntitys.size()-1){
                mPlayPosition=playPosition;
                mIsPlay=true;
                mAdapter.setReaderId(mProjectListEntitys.get(mPlayPosition).getReaderId());
                getReaderInfo(mProjectListEntitys.get(mPlayPosition).getReaderId());
                setVideo("");
            }
        }
    }

    private void getReaderList(){
        int readerTypeId;
        if(businessInfoDid!=null){
            readerTypeId=businessInfoDid.getReaderTypeId();
        }else if(readerInfo!=null){
            readerTypeId=readerInfo.getReaderTypeId();
        }else{
            return;
        }
        HashMap postMap=new HashMap();
        postMap.put("readerTypeId",String.valueOf(readerTypeId));
        String url=Urls.getReaderList(mPageNum, 10,"asc");
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url,postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                hideLoading();
                ProjectListEntity readerLists = gson.fromJson(result, ProjectListEntity.class);
                if(readerLists.getCode()==0){
                    totalPage=readerLists.getPage().getTotalPage();
                    if(refresh && mAdapter!=null){
                        mAdapter.removeAllHeader();
                        mAdapter.clear();
                        mProjectListEntitys.clear();
                    }
                    mProjectListEntitys.addAll(readerLists.getPage().getList());
                    mAdapter.addAll(readerLists.getPage().getList());
                    if(mPageNum>=totalPage && mAdapter!=null){
                        try {
                            mAdapter.pauseMore();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    myApplication.setProjectListEntitys(mProjectListEntitys);
                }
                if(mAdapter!=null){
                    mAdapter.notifyDataSetChanged();
                }
                for(int i=0;i<mProjectListEntitys.size();i++){
                    mradioUrls.add(mProjectListEntitys.get(i).getUrl());
                }
                mIsFirst=false;
                MyApplication myApplication=new MyApplication();

                setVideo(mProjectListEntitys.get(mPlayPosition).getUrl());
                setDiaglog();
            }
        });
    }

    private List<String> mradioUrls=new ArrayList<>();

    private void setDiaglog(){
        if(mBottomDialog!=null){
            return;
        }
        View outerView = LayoutInflater.from(RadioActivity.this).inflate(R.layout.dialog_radio_list, null);
        TextView tv_clean=outerView.findViewById(R.id.tv_clean);
        TextView tv_close=outerView.findViewById(R.id.tv_close);
        YCRefreshView ycRefreshView=outerView.findViewById(R.id.ycRefreshView);
        ycRefreshView.setLayoutManager(new LinearLayoutManager(RadioActivity.this));
        ycRefreshView.setEmptyView(R.layout.empty_view_layout);
        ycRefreshView.setAdapter(mAdapter);

        mAdapter.setMore(R.layout.view_more, () -> {
            //可以做请求下一页操作
            mPageNum++;
            refresh=false;
            getReaderList();
        });
        ycRefreshView.setRefreshListener(() -> {
            mPageNum= 1;
            refresh=true;
            getReaderList();
        });
        tv_clean.setOnClickListener(v -> {
            if(mCenterDialog==null){
                setCenterDiaglog();
            }
            mCenterDialog.show();
        });
        tv_close.setOnClickListener(v -> mBottomDialog.dismiss());
        //防止弹出两个窗口
        if (mBottomDialog !=null && mBottomDialog.isShowing()) {
            return;
        }

        mBottomDialog = new BottomDialog(RadioActivity.this, R.style.ActionSheetDialogBotoomStyle);
        //将布局设置给Dialog
        mBottomDialog.setContentView(outerView);
        //mBottomDialog.show();//显示对话框
    }
    private BottomDialog mBottomDialog;
    private CenterDialog mCenterDialog;
    private void setCenterDiaglog(){
        View outerView = LayoutInflater.from(RadioActivity.this).inflate(R.layout.dialog_deletes, null);
        Button btn_ok=outerView.findViewById(R.id.btn_ok);
        Button btn_cancel=outerView.findViewById(R.id.btn_cancel);
        TextView tv_title=outerView.findViewById(R.id.tv_title);
        tv_title.setText("是否确认清空？");
        btn_ok.setOnClickListener(v -> {
            mJcVideoPlayerStandard.clearUrl();
            mProjectListEntitys.clear();
            mAdapter.clear();
            mAdapter.notifyDataSetChanged();
            mCenterDialog.dismiss();
        });
        btn_cancel.setOnClickListener(v -> mCenterDialog.dismiss());
        //防止弹出两个窗口
        if (mCenterDialog !=null && mCenterDialog.isShowing()) {
            return;
        }

        mCenterDialog = new CenterDialog(RadioActivity.this, R.style.ActionSheetDialogBotoomStyle);
        //将布局设置给Dialog
        mCenterDialog.setContentView(outerView);
    }
}
